<template>
  <!-- 修改资质信息 -->
  <view class="placeAptitude">
    <view class="wrapper">
      <view class="wrapper-item content">
        <u-form :model="form" ref="form" label-width="100" :error-type="errorType">
          <view class="title-name">营业执照</view>
          <u-form-item label="证件图片" label-width="70">
            <text style="color: #a1a1a1; font-size: 26rpx"> (大小2M以内) </text>
          </u-form-item>
          <u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic(1)" name="file" :maxCount="1"
            width="100" height="80">
            <image :src="baseImgUrl + 'upload-icon3.png'" style="width: 200rpx; height: 160rpx"></image>
          </u-upload>

          <u-form-item label="企业名称" borderBottom label-width="70">
            <u--input v-model.trim="form.businessName" border="none" placeholder="请填写" :maxlength="18"></u--input>
          </u-form-item>

          <u-form-item label="信用代码" borderBottom label-width="70">
            <u--input v-model.trim="form.creditCode" border="none" placeholder="请填写" :maxlength="22"></u--input>
          </u-form-item>

          <block v-if="options.lvguan == '旅馆业'">
            <view class="title-name" style="padding-top: 35rpx">
              特种行业许可证
            </view>
            <u-form-item label="证件图片" label-width="70">
              <text style="color: #a1a1a1; font-size: 26rpx">
                (大小2M以内)
              </text>
            </u-form-item>
            <u-upload :fileList="fileList2" @afterRead="afterRead2" @delete="deletePic(2)" name="file" :maxCount="1"
              width="310" height="215" imageMode="aspectFill" :delIconCenter="true" :delIconSize="40">
              <image :src="baseImgUrl + 'card_2.png'" style="width: 640rpx; height: 430rpx"></image>
            </u-upload>
            <u-form-item label="证书编码" label-width="70">
              <view class="special-class">
                <view>
                  <u--input v-model.trim="form.ccieFirst" border="bottom" :maxlength="2"></u--input>
                  <span>公特</span>
                </view>
                <view>
                  <u--input v-model.trim="form.ccieSecond" border="bottom" :maxlength="2"></u--input>
                  <span>字第</span>
                </view>
                <view>
                  <u--input v-model.trim="form.ccieThird" border="bottom" :maxlength="8"></u--input>
                  <span>号</span>
                </view>
              </view>
            </u-form-item>
            <u-form-item label="发证机关" borderBottom label-width="70">
              <u--input v-model.trim="form.certificateOffice" border="none" placeholder="请填写"
                :maxlength="18"></u--input>
            </u-form-item>

            <u-form-item label="发证日期" borderBottom label-width="70" @click="cellTimeClick('certificateDate')">
              <u--input v-model="form.certificateDateName" disabled disabledColor="#ffffff" placeholder="请选择"
                border="none"></u--input>
              <image :src="baseImgUrl + 'day-icon.png'" mode="" slot="right" class="seleTime"></image>
            </u-form-item>
          </block>
        </u-form>
      </view>
    </view>

    <view class="btns thispageBtn">
      <button class="cancel-btn lt" type="primary" @click="navBack('back', 1, 1)">
        取消
      </button>
      <button class="submit-btn" type="primary" @click="submitHandle">
        保存
      </button>
    </view>

    <canvas canvas-id="myCanvas" :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }"
      style="position: fixed; top: -9999999999999rpx" @error="error"></canvas>

    <!-- 时间选择器 -->
    <u-datetime-picker ref="datetimePicker" :show="datetimeShow" v-model="timeValue" mode="date" :formatter="formatter"
      :minDate="minDate" :maxDate="maxDate" @close="pickerTimeClose" @cancel="pickerTimeClose(1)"
      @confirm="showTimeConfirm" :closeOnClickOverlay="true"></u-datetime-picker>
    <yy-watermark></yy-watermark>
  </view>
</template>

<script>
  import {
    businessDetail,
    certificateDetail,
    updateCompany,
    smartStructuralOrc,
  } from "@/api/myself.js";
  import {
    Toast,
    navBack,
    handleClickRouter,
    uniTrim,
    formatters,
    dayTurnTime,
    checkSocialCardNumber,
    medicalTreatment,
    registerNumber,
    getBase64Two,
    useNetWork,
    isLoading,
    getHeader,
    uploadFile,
  } from "@/utils/util.js";
  import mixin from "@/utils/mixin.js";

  export default {
    name: "placeAptitude",
    mixins: [mixin],
    data() {
      return {
        baseImgUrl: this.$baseImgUrl,
        baseURL: this.$baseURL,
        clientId: this.$clientId,
        clientSecret: this.$clientSecret,
        imgPrefix: uni.getStorageSync("imgPrefix"),
        options: {},
        form: {},
        errorType: ["none"],
        fileList: [],
        fileList2: [],
        canvasWidth: 0,
        canvasHeight: 0,
      };
    },
    onLoad(options) {
      this.options = options;
      businessDetail({
        companyId: options.id
      }).then((res) => {
        if (res.code == 200) {
          this.form = res.result;

          if (this.form.businessLicenseUrl) {
            this.fileList.push({
              url: this.imgPrefix + this.form.businessLicenseUrl,
            });
          }
        }
      });

      // certificateDetail({
      //   companyId: options.id
      // }).then((res) => {
      //   let {
      //     code,
      //     result
      //   } = res;
      //   if (code == 200) {
      //     this.form = {
      //       ...this.form,
      //       ...result
      //     };
      //     this.form.ccieFirst = result.certificateCodeList[0];
      //     this.form.ccieSecond = result.certificateCodeList[1];
      //     this.form.ccieThird = result.certificateCodeList[2];
      //     if (result.certificateTime) {
      //       this.form.certificateDateName = formatters(
      //         result.certificateTime,
      //         "YY/MM/DD"
      //       );
      //       this.form.certificateDate = dayTurnTime(
      //         this.form.certificateDateName
      //       );
      //     }

      //     if (this.form.certificateUrl) {
      //       this.fileList2.push({
      //         url: this.imgPrefix + this.form.certificateUrl,
      //       });
      //     }
      //   }
      // });
    },
    methods: {
      handleClickRouter,
      navBack,
      error(e) {
        console.log(e, "图片沪指错误");
      },
      formatter(type, value) {
        if (type === "year") {
          return `${value}年`;
        }
        if (type === "month") {
          return `${value}月`;
        }
        if (type === "day") {
          return `${value}日`;
        }
        return value;
      },
      cellTimeClick(e) {
        this.cellType = e;
        var minDateNum = +new Date(); //获取当前时间的毫秒数

        switch (this.cellType) {
          case "certificateDate":
            this.maxDate = minDateNum;
            this.timeValue = this.maxDate;
            break;
          default:
            break;
        }

        setTimeout(() => {
          this.datetimeShow = true;
        }, 100);
      },
      pickerTimeClose(e) {
        if (e) {
          switch (this.cellType) {
            case "certificateDate":
              this.form.certificateDate = "";
              this.form.certificateDateName = "";
              break;
            default:
              break;
          }
        }
        this.datetimeShow = false;
      },
      /* 时间选择器 确定 */
      showTimeConfirm(e) {
        let arr = e.value;
        if (arr) {
          switch (this.cellType) {
            case "certificateDate":
              this.form.certificateDateName = formatters(arr, "YY/MM/DD");
              this.form.certificateDate = dayTurnTime(
                this.form.certificateDateName
              );
              break;

            default:
              break;
          }
        }
        this.datetimeShow = false;
      },
      afterRead(info) {
        let _this = this;

        uni.request({
          url: "https://aip.baidubce.com/oauth/2.0/token",
          method: "GET",
          data: {
            grant_type: "client_credentials",
            client_id: _this.clientId,
            client_secret: _this.clientSecret,
          },
          success(res) {
            _this.base64Business(res.data.access_token, info);
          },
        });
      },
      base64Business(token, info) {
        let _this = this;

        getBase64Two(info.file.url)
          .then((res) => {
            return res;
          })
          .then((res) => {
            uni.request({
              url: `https://aip.baidubce.com/rest/2.0/ocr/v1/business_license?access_token=${token}`,
              method: "POST",
              header: {
                "Content-Type": "application/x-www-form-urlencoded",
              },
              data: {
                id_card_side: "front",
                image: res,
                detect_direction: true,
              },
              // success(resbai) {
              //   let { statusCode, data } = resbai;
              //   if (statusCode == 200 && data.words_result) {
              //     _this.$set(
              //       _this.form,
              //       "businessName",
              //       data.words_result.单位名称.words
              //     );
              //     _this.$set(
              //       _this.form,
              //       "creditCode",
              //       data.words_result.社会信用代码.words
              //     );
              //     _this.uploadImage(info.file.url, 2);
              //     return;
              //   }

              //   Toast("未识别");
              //   _this.uploadImage(info.file.url, 2);
              //   // Toast("请上传正确的营业执照");
              // },
              success(resbai) {
                let {
                  statusCode,
                  data
                } = resbai;
                _this.uploadImage(info.file.url, 2);
                if (statusCode == 200 && data && data.words_result && data.words_result["单位名称"]) {
                  _this.$set(
                    _this.form,
                    "businessName",
                    data.words_result.单位名称.words
                  );
                  _this.$set(
                    _this.form,
                    "creditCode",
                    data.words_result.社会信用代码.words
                  );

                  // 图片旋转  start
                  var yingNum = 0;
                  var direction = data.direction;
                  if (direction != -1 && direction != 0) {
                    if (direction == 1) {
                      //逆时针90°
                      yingNum = 90;
                    } else if (direction == 2) {
                      //逆时针180°
                      yingNum = 180;
                    } else if (direction == 3) {
                      //逆时针270°
                      yingNum = 270;
                    }
                  }

                  if (yingNum) {
                    _this.drapImgLast(info, yingNum);
                    return;
                  }
                  return;
                }
              },
            });
          });
      },
      drapImgLast(info, yingNum) {
        let _this = this;
        const ctx = uni.createCanvasContext("myCanvas", _this);

        uni.getImageInfo({
          src: info.file.url,
          success(res1) {
            let {
              width,
              height,
              path
            } = res1;
            if (yingNum == 90) {
              _this.canvasWidth = height;
              _this.canvasHeight = width;
              ctx.clearRect(0, 0, width, width); // 清空画布

              ctx.translate(_this.canvasWidth, 0);
              ctx.rotate((yingNum * Math.PI) / 180);
            } else if (yingNum == 270) {
              _this.canvasWidth = height;
              _this.canvasHeight = width;
              ctx.clearRect(0, 0, height, width); // 清空画布

              ctx.translate(0, _this.canvasHeight - 10);
              ctx.rotate((yingNum * Math.PI) / 180);
            } else if (yingNum == 180) {
              _this.canvasWidth = width;
              _this.canvasHeight = height;
              ctx.clearRect(0, 0, width, height); // 清空画布

              ctx.translate(_this.canvasWidth, _this.canvasHeight);
              ctx.rotate((-yingNum * Math.PI) / 180);
            }
            // ctx.drawImage(path, 0, 0, width, height);
            ctx.drawImage(path, 0, 0);

            // 将生成的canvas图片，转为真实图片
            ctx.draw(false, () => {
              setTimeout(() => {
                uni.canvasToTempFilePath({
                  x: 0,
                  y: 0,
                  canvasId: "myCanvas",
                  success(res2) {
                    console.log(res2, "RRRRRRRRR");
                    _this.uploadImage(res2.tempFilePath, 2);
                  },
                });
              }, 50);
            });
          },
        });
      },
      uploadImage(fileurl, type) {
        useNetWork(); // 判断是否有网络
        isLoading();
        let _this = this;

        uploadFile({
            url: "/web/sys/upload/upload_file",
            filePath: fileurl,
            name: "file",
            formData: {
              type: type,
            },
          })
          .then((res) => {
            isLoading(false);
            let {
              fullPath,
              halfPath
            } = res.result;

            if (type == 2) {
              // 营业执照的
              _this.fileList.push({
                url: fullPath
              });
              _this.form.businessLicenseUrl = halfPath;
            }
          })
          .finally(() => {
            isLoading(false);
          })
      },
      afterRead2(info) {
        let _this = this;
        getBase64Two(info.file.url)
          .then((res) => {
            return res;
          })
          .then((res) => {
            smartStructuralOrc({
              imageBase64: res
            }).then((res) => {
              // if (res.code != 200) return Toast("请上传正确的特种行业许可证");
              if (res.code != 200) {
                Toast("未识别");
                _this.ocrPicHandle(null, info.file.url);
                return;
              }

              var ocrList = res.result.structuralItems;
              var indexName = ocrList.map((v) => v.name).indexOf("标题");
              var indexvalue = ocrList
                .map((v) => v.value)
                .indexOf("特种行业许可证");

              if (indexName != -1 && indexvalue != -1) {
                _this.ocrPicHandle(ocrList, info.file.url);
                return;
              }

              Toast("未识别");
              _this.ocrPicHandle(null, info.file.url);
            });
          });
      },
      ocrPicHandle(ocrList, urlimg) {
        if (ocrList) {
          ocrList.map((v) => {
            if (v.name == "证字号") {
              let nameV = v.value;
              let gt = nameV.lastIndexOf("公特");
              let zd = nameV.lastIndexOf("字第");
              let num = nameV.lastIndexOf("号");

              let firsta = nameV.slice(0, nameV);
              let firsts = nameV.slice(gt + 2, zd);
              let firstt = nameV.slice(zd + 2, num);
              this.$set(this.form, "ccieFirst", firsta || "");
              this.$set(this.form, "ccieSecond", firsts || "");
              this.$set(this.form, "ccieThird", firstt);
            }

            if (v.name == "日期") {
              let year = v.value.lastIndexOf("年");
              let month = v.value.lastIndexOf("月");
              let day = v.value.lastIndexOf("日");

              var da1 = v.value.slice(0, year); //年
              var da2 = v.value.slice(year + 1, month); // 月
              var da3 = v.value.slice(month + 1, day); // 日
              let gTime = dayTurnTime(`${da1}/${da2}/${da3}`);
              this.form.certificateDateName = formatters(gTime, "YY/MM/DD");
              this.form.certificateDate = gTime;
            }
          });
        }

        useNetWork(); // 判断是否有网络
        isLoading();
        let _this = this;
        uploadFile({
            url: "/web/sys/upload/upload_file",
            filePath: urlimg,
            name: "file",
            formData: {
              type: 17,
            },
          })
          .then((res) => {
            isLoading(false);
            let {
              fullPath,
              halfPath
            } = res.result;
            _this.fileList2 = [];
            _this.fileList2.push({
              url: fullPath
            });
            _this.form.certificateUrl = halfPath;
          })
          .finally(() => {
            isLoading(false);
          })
      },
      deletePic(num) {
        if (num == 1) {
          this.fileList = [];
          this.form.businessLicenseUrl = "";
        } else if (num == 2) {
          this.fileList2 = [];
          this.form.certificateUrl = "";
        }
      },
      submitHandle() {
        let {
          businessLicenseUrl,
          businessName,
          creditCode,
          certificateUrl,
          ccieFirst,
          ccieSecond,
          ccieThird,
          certificateOffice,
          certificateDate,
        } = this.form;
        // if (!businessLicenseUrl) {
        //   Toast("请上传营业执照");
        //   return;
        // }

        // if (!businessName || !uniTrim(businessName)) {
        //   Toast("请输入企业名称");
        //   return;
        // }

        // if (!creditCode || !uniTrim(creditCode)) {
        //   Toast("请输入信用代码");
        //   return;
        // }

        // let check = checkSocialCardNumber(creditCode);
        // let medical = medicalTreatment(creditCode);
        // let refisNum = registerNumber(creditCode);
        // if (!check && !medical && !refisNum) {
        //   Toast("请输入正确的信用代码");
        //   return;
        // }
        if (this.options.lvguan == "旅馆业") {
          if (
            certificateUrl ||
            ccieThird ||
            certificateOffice ||
            certificateDate
          ) {
            if (!certificateUrl) {
              Toast("请上特殊行业许可证照片");
              return;
            }

            if (!ccieThird || !uniTrim(ccieThird)) {
              Toast("请输入证书编码");
              return;
            }

            if (!certificateOffice || !uniTrim(certificateOffice)) {
              Toast("请输入发证机关");
              return;
            }

            if (!certificateDate) {
              Toast("请选择发证日期");
              return;
            }
          }
        }

        let data = {
          companyQualificationsInfo: {
            id: this.options.id,
            creditCode: creditCode,
            businessName: businessName,
            businessLicenseUrl: businessLicenseUrl,
            certificateCodeList: ccieThird ? [ccieFirst || "", ccieSecond || "", ccieThird] : [],
            certificateUrl: certificateUrl,
            certificateOffice: certificateOffice,
            certificateDate: certificateDate,
          },
        };

        updateCompany(data).then((res) => {
          if (res.code == 200) {
            Toast("保存成功");
            navBack("back");
            return;
          }
          Toast(res.message);
        });
      },
    },
  };
</script>

<style>
  page {
    background-color: #f3f3f3 !important;
    height: 100%;
  }
</style>
<style lang="scss" scoped>
  .placeAptitude {
    flex: 1;
    background-color: #f3f3f3;

    .placeAptitude-title {
      position: absolute;
      top: 10rpx;
      left: 6%;
      color: #ffffff;
      font-size: 34rpx;
      font-weight: bold;
    }

    .wrapper {
      position: absolute;
      top: 30rpx;
      left: 50%;
      transform: translateX(-50%);

      .wrapper-item {
        margin-bottom: 2vh;
        padding: 35rpx 30rpx;
        background-color: #ffffff;
        border-radius: 10rpx;
        width: 702rpx;
      }

      .content {
        margin: 0 auto;
        height: calc(100vh - 90px);
        overflow-y: auto;
      }
    }

    .title-name {
      font-size: 30rpx;
      font-weight: bold;
    }

    .special-class {
      display: flex;

      view {
        width: 160rpx;
        display: flex;

        /deep/.u-input {
          width: 60% !important;
        }
      }

      view:nth-of-type(3) {
        width: 180rpx;
      }

      /deep/input {
        padding-right: 0;
      }

      span {
        padding-top: 18rpx;
        font-size: 30rpx;
      }
    }

    .seleTime {
      width: 45rpx;
      height: 45rpx;
    }

    .thispageBtn {
      position: absolute;
      width: 100vw;
      bottom: 0;
    }
  }
</style>